<?php

namespace App\Models;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Model;
use App\Traits\HasDateTimeFormatter;

class HhmOrderGoods extends BaseModel
{
    use HasDateTimeFormatter;
    
    protected $table = 'ims_hhm_order_goods';
    protected $guarded = [''];
    
    // 补充SQL表中的所有字段到 fillable 数组
    protected $fillable = [
        'order_id', 'goods_id', 'total', 'create_at', 'price', 'uid',
        'thumb', 'title', 'goods_price', 'goods_option_id', 'goods_option_title',
        'created_at', 'updated_at', 'discount_price', 'comment_status',
        'change_price', 'comment_id', 'market_price', 'cost_price',
        'payment_amount', 'deduction_amount', 'need_address', 
        'order_express_id', 'is_refund'
    ];
    
    protected $casts = [
        'goods_option_ids' => 'json',
        'goods_info' => 'json'
    ];

    // 禁用Laravel的自动时间戳管理
    public $timestamps = true;
    
    /**
     * 关联订单
     */
    public function order()
    {
        return $this->belongsTo(Order::class, 'order_id', 'id');
    }
    
    /**
     * 关联商品
     */
    public function goods()
    {
        return $this->belongsTo(Goods::class, 'goods_id', 'id');
    }
    
    /**
     * 按订单ID筛选
     */
    public function scopeByOrderId($query, $orderId)
    {
        return $query->where('order_id', $orderId);
    }
    
    /**
     * 按商品ID筛选
     */
    public function scopeByGoodsId($query, $goodsId)
    {
        return $query->where('goods_id', $goodsId);
    }
    
    /**
     * 获取商品总价
     */
    public function getTotalPriceAttribute()
    {
        return $this->price * $this->total;
    }
}
